﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Threading;
using System.Data.SqlClient;
using sql表结构对比.ViewModel;
using sql表结构对比.Model;
using sql表结构对比.Repository;
using sql表结构对比.IRepository;
using sql表结构对比.DataBusinessLayer;
namespace sql表结构对比
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();

        }

        //测试连接按钮单击功能
        private void btnLink_Click(object sender, EventArgs e)
        {
            initialState();
            stateLabel.Text = "连接中...";
            TestLink();
        }

        //执行按钮单击功能
        private void btnSubmit_Click(object sender, EventArgs e)
        {
            initialState();
            stateProgressbar.Maximum = 100;
            stateLabel.Text = "执行中...";
            Submit();
        }

        //单击数据迁移选项卡时
        private void tabControl2_SelectedIndexChanged(object sender, EventArgs e)
        {
            initialState();
            if (tabControl2.SelectedTab == this.tabPage4)
            {
                this.txtSourceSql.Text = this.combSourceSql.Text;
                this.txtDestSql.Text = this.comDestinationSql.Text;
                if (txtSourceSql.Text == "" || txtDestSql.Text == "")
                {
                    btnSubmit.Enabled = false;
                    txtErrorWorklog.Text = "您还没有选择数据库。\r\n请进入服务器登录界面，选择数据库。否则无法进行下一步操作";
                }
          
                tables = comb_wx_tbs.Text;
                txtErrorWorkloginfo1.Visible = true;
                panel1.Visible = false;
                List<string> basicinfo = GetBasicInfo();
                if (tabControl1.SelectedTab == this.tabPage2)
                {
                    tb_Dictionary dic = new tb_Dictionary(GetBasicInfo());
                    if (dic.tb_dic.Keys.Count == 0)
                    {
                        comb_HQHOS_Tbs.DataSource = null;
                        comb_HQHOS_Tbs.Items.Clear();
                    }
                    else
                    {
                        comb_wx_tbs.DataSource = dic.tb_dic.Keys.ToList();
                        comb_HQHOS_Tbs.DataSource = dic.tb_dic.Values.ToList();
                    }
                    
                    //建立线程加载组织代码
                    //D_show = new D_showComb(D_showMethod);
                    //Thread thread = new Thread(new ThreadStart
                    //    (ThreadMethod));
                    //thread.IsBackground = true;
                    //thread.Start();

                }
                comboBox5.DataSource = combSourceSql.Items;
            }


        }

        //一键导入功能
        private void toolStripMenuItem1_Click(object sender, EventArgs e)
        {

            if (comb_wx_tbs.Text == "" || comb_HQHOS_Tbs.Text == "")
            {
                txtErrorWorkloginfo1.Text = "表名不能为空，请选择相应表名。";
            }
            else
            {
                string info = "";
                if (SqlHelper.Connection(GetConnstrInfo(), out  info))
                {
                    initialState();
                    stateProgressbar.Maximum = 0;
                    txtErrorWorkloginfo1.Text = "";
                    basicinfo = GetBasicInfo();
                    wx_tb = comb_wx_tbs.Text;
                    OrgId = comboBox3.Text;
                    option = comboBox3.Text;
                    basicinfo.Add(comb_wx_tbs.Text);
                    basicinfo.Add(comb_HQHOS_Tbs.Text);
                    D_show_info = new D_show_workloginfo(D_show_worklog);
                    Common.curProgress = 0;
                    Thread thread = new Thread(threadstart_Dimport);
                    thread.IsBackground = true;
                    thread.Start();
                    //timer1.Enabled = true;
                }
                else
                {
                    txtErrorWorkloginfo1.Text = info;
                }

            }


        }
        //数据库表名加载
        #region
        private void txtSourceSql_TextChanged(object sender, EventArgs e)
        {
            //加载源数据库表名
            //GetSourTables(combSourceTbs);
            //Thread.Sleep(5);
        }
        private void txtDestSql_TextChanged(object sender, EventArgs e)
        {
            //加载目的数据库表名
            //GetDesTables();
        }
        #endregion

        //专用数据表,下拉框关系绑定
        #region
        private void comb_wx_tbs_TextChanged(object sender, EventArgs e)
        {
            Common cm = new Common();
            string str = string.Empty;
            cm.BindTable(comb_wx_tbs.Text, GetBasicInfo(), out str);
            comb_HQHOS_Tbs.Text = str;
            //IDedicatedService IDe = new DedicatedService();
            //comboBox3.DataSource = IDe.BindCombBox(comb_wx_tbs.Text);
        }
        private void comb_HQHOS_Tbs_TextChanged(object sender, EventArgs e)
        {
            Common cm = new Common();
            string str = string.Empty;
            cm.BindTable(comb_HQHOS_Tbs.Text, GetBasicInfo(), out str);
            comb_wx_tbs.Text = str;
        }
        #endregion

        //切换至专用功能卡页时
        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            initialState();
            tables = comb_wx_tbs.Text;
            txtErrorWorkloginfo1.Visible = true;
            panel1.Visible = false;
            if (tabControl2.SelectedTab == this.tabPage4)
            {
                this.txtSourceSql.Text = this.combSourceSql.Text;
                this.txtDestSql.Text = this.comDestinationSql.Text;
                if (txtSourceSql.Text == "" || txtDestSql.Text == "")
                {
                    btnSubmit.Enabled = false;
                    txtErrorWorklog.Text = "您还没有选择数据库。\r\n请进入服务器登录界面，选择数据库。否则无法进行下一步操作";
                }

                initialState();
                tables = comb_wx_tbs.Text;
                txtErrorWorkloginfo1.Visible = true;
                panel1.Visible = false;
                List<string> basicinfo = GetBasicInfo();
                if (tabControl1.SelectedTab == this.tabPage2)
                {
                    tb_Dictionary dic = new tb_Dictionary(GetBasicInfo());
                    if (dic.tb_dic.Keys.Count == 0)
                    {
                        comb_HQHOS_Tbs.DataSource = null;
                        comb_HQHOS_Tbs.Items.Clear();


                    }
                    else
                    {
                        comb_wx_tbs.DataSource = dic.tb_dic.Keys.ToList();
                        comb_HQHOS_Tbs.DataSource = dic.tb_dic.Values.ToList();
                    }

                    //建立线程加载组织代码
                    //D_show = new D_showComb(D_showMethod);
                    //Thread thread = new Thread(new ThreadStart
                    //    (ThreadMethod));
                    //thread.IsBackground = true;
                    //thread.Start();

                }
            }
        }
        //单击确认配置
        #region
        private void btnOk(object sender, EventArgs e)
        {
            txtErrorWorkloginfo1.Visible = true;
            panel1.Visible = false;
            List<string> relation = GetAllvalue(checkedListBox2);
            DedicatedService ds = new DedicatedService();
            List<string> basicinfo = GetBasicInfo();
            basicinfo.Add(comboBox1.Text);
            basicinfo.Add(comboBox2.Text);
            if (ds.comfirm(basicinfo) == null)
            {
                ds.AddTableRelationship(relation, basicinfo);
            }
            else
            {
                ds.UpdataTableRelationship(basicinfo, relation);
            }
            txtErrorWorkloginfo1.Text = "";
            tb_Dictionary dic = new tb_Dictionary(GetBasicInfo());
            if (dic.tb_dic.Keys.Count == 0)
            {
                comb_HQHOS_Tbs.DataSource = null;
                comb_HQHOS_Tbs.Items.Clear();
            }
            else
            {
                comb_wx_tbs.DataSource = dic.tb_dic.Keys.ToList();
                comb_HQHOS_Tbs.DataSource = dic.tb_dic.Values.ToList();
            }
        }

        //点击新建表关系
        private void toolStripMenuItem2_Click(object sender, EventArgs e)
        {
            txtErrorWorkloginfo1.Visible = false;
            panel1.Visible = true;
            comboBox1.DataSource = combSourceTbs.Items;
            comboBox2.DataSource = combDesTbs.Items;

        }

        //单击取消按钮
        private void btnCancel_Click(object sender, EventArgs e)
        {
            txtErrorWorkloginfo1.Visible = true;
            panel1.Visible = false;
            timer2.Enabled = false;
        }
        #endregion

        //获取选定表的字段名
        #region
        private void comboBox1_TextChanged(object sender, EventArgs e)
        {
            checkedListBox1.Items.Clear();
            List<string> basicinfo = GetBasicInfo();
            basicinfo.Add(comboBox1.Text);
            basicinfo.Add(comboBox2.Text);
            showRelationship(basicinfo);
            GetColumnNames(comboBox1.Text, SqlHelper.constrSocurce, checkedListBox1);
        }
        private void comboBox2_TextChanged(object sender, EventArgs e)
        {
            checkedListBox3.Items.Clear();
            checkedListBox2.Items.Clear();
            List<string> basicinfo = GetBasicInfo();
            basicinfo.Add(comboBox1.Text);
            basicinfo.Add(comboBox2.Text);
            showRelationship(basicinfo);
            GetColumnNames(comboBox2.Text, SqlHelper.constrDest, checkedListBox3);
        }
        #endregion

        //给checklistbox设置单选
        #region
        private void checkedListBox1_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            selectJustOne(sender, e, checkedListBox1);
        }

        private void checkedListBox3_ItemCheck(object sender, ItemCheckEventArgs e)
        {
            selectJustOne(sender, e, checkedListBox3);
            timer2.Enabled = true;
        }

        #endregion

        //点击解绑
        private void 解绑ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (var item in GetCheckedItemsText(checkedListBox2))
            {
                checkedListBox2.Items.Remove(item);
                string[] temp = item.Split(new char[2] { '-', '>' });
                if (checkedListBox1.Items.Contains(temp[0]))
                {

                }
                else
                {
                    checkedListBox1.Items.Add(temp[0]);
                }
                if (checkedListBox3.Items.Contains(temp[2]))
                {

                }
                else
                {
                    checkedListBox3.Items.Add(temp[2]);
                }

            }
        }
        //数据库名字更改时，加载相应的表名
        #region
        private void combSourceSql_TextChanged(object sender, EventArgs e)
        {
            GetSourTables(combSourceTbs);
        }
        private void comDestinationSql_TextChanged(object sender, EventArgs e)
        {
            GetDesTables();
        }

        #endregion
        //全选功能
        #region
        bool mutex = true;
        private void ckAll_CheckStateChanged(object sender, EventArgs e)
        {

            if (mutex)
            {

                mutex = SelectALL();
            }
            else
            {
                mutex = CancelALL();
            }
        }
        #endregion

        private void Form1_Load(object sender, EventArgs e)
        {
            DedicatedService des = new DedicatedService();
            foreach (tablerelationship item in des.GetTableRelationship())
            {

                if (combSourceSql.Items.Contains(item.basicinfo[0]))
                {

                }
                else
                {
                    combSourceSql.Items.Add(item.basicinfo[0]);
                    comDestinationSql.Items.Add(item.basicinfo[0]);
                }
                if (combSourceSql.Items.Contains(item.basicinfo[1]))
                {

                }
                else
                {
                    combSourceSql.Items.Add(item.basicinfo[1]);
                    comDestinationSql.Items.Add(item.basicinfo[1]);
                }

            }

        }
        //单击浏览按钮
        private void btn_scan_Click(object sender, EventArgs e)
        {
            OpenFileDialog fd = new OpenFileDialog();
            fd.Filter = "Excel文件|*.xls;*.xlsx";
            if (fd.ShowDialog() == DialogResult.OK)
            {
                txtExcelName.Text = fd.FileName;
            }
            string errorinfo1 = "";
            comboBox4.DataSource = GetSheetNames(fd.FileName, out errorinfo1);
            if (errorinfo1 == "")
            {
            }
            else
            {
                comboBox4.DataSource = null;
                comboBox4.Items.Clear();
                MessageBox.Show(errorinfo1 + "\r\n" + "请重新添加excel文件");
            }
        }
        //一键导入按钮（excel表格）
        private void button2_Click(object sender, EventArgs e)
        {
            Common cm = new Common();
            string config = cm.GetExcelConfig(GetConnstrInfo());
            config += comboBox5.Text;

            string error = "";
            if (match(comboBox4)) {
                if (comboBox5.Text == "") {
                    richTextBox1.Text ="数据库名不能为空！请输入一个正确的数据库名.";
                }
                else
                {
                    if (TransferData(txtExcelName.Text, comboBox4.Text, config,textBox1.Text ,out error))
                    {
                        richTextBox1.Text = "表格" + comboBox4.Text + "已成功导入" + comboBox5.Text + "中";
                    }
                    else
                    {
                        if (error.Contains("该表并没有内容！请重新选择吧"))
                        {
                            richTextBox1.Text = error;
                        }
                        else
                        {
                            richTextBox1.Text = error + "\r\n请检查登录信息是否正确.以及表名是否选择正确.";
                        }
                       
                    }
                }
            }
            else
            {
                richTextBox1.Text = "如果您还没有选择一个Excel文件,请进行选择.\r\n如果您输入的表名在Excel文件中并不包含，请重新输入.\r\n为了防止您输入错误,建议您从下拉框中去选择.";
            }
        }

        private void label25_Click(object sender, EventArgs e)
        {

        }

        private void txtServerIP_TextChanged(object sender, EventArgs e)
        {
          
        }

        private void 刷新ToolStripMenuItem_Click(object sender, EventArgs e)
        {
          if(TestLink()){
              txtErrorWorkloginfo1.Text = "";
          }
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {

            GetSourTables(combSourceTbs);
            Thread.Sleep(20);
            GetDesTables();
        }

        private void 生成sql语句ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            basicinfo = GetBasicInfo();
            basicinfo.Add(comb_wx_tbs.Text);
            basicinfo.Add(comb_HQHOS_Tbs.Text);
            DedicatedService dts = new DedicatedService();
            string cmd=  dts.command(basicinfo);
            txtErrorWorkloginfo1.Text += "\r\n"+cmd;
        }

     
    }
}
